#include <unistd.h>
#include <sys/types.h>
#include <syslog.h>
#include <sys/types.h>
#include <stdio.h>
#include <sys/stat.h>
#include "CL_News_pool.h"
#include <fstream>
#include <boost/regex.hpp>
#include <ios>
#include <iostream>
#include <string>

void CL_News_pool::mylog(const std::string c, const std::string m, int prio)
{
    if(prio<0 ||prio>7) return;
    openlog(progname, LOG_PID, LOG_USER);
    setlogmask(message_level);
    syslog(prio, "%s: %s [user:%s][class:%s]",prioritystrings[prio],m.c_str(), username.c_str(),c.c_str());
    closelog();
};

std::string CL_News_pool::CL_RSS_Quelle::write_request_response_2_file(Poco::Net::HTTPRequest& request,Poco::Net::HTTPResponse& response)
{
    std::string filename("");
    std::ostringstream o(filename);
    o<<userhome<<"/."<<progname;
    o.flush();
    filename=o.str();
    if(access(o.str().c_str(),06))
    {

        if(mkdir(o.str().c_str(),S_IRWXU))
        {
            mylog("CL_News_pool::CL_RSS_Quelle::write_request_response_2_file",o.str()+" coudn't be created.",LOG_ERR);
            return "";
        }
    }
    o<<"/"<<"reqres"<<time(NULL)<<".log";
    std::ofstream of(o.str().c_str());
    of<<"Request:"<<std::endl<<"##############################################"<<std::endl;
    request.write(of);
    of<<"Response:"<<std::endl<<"##############################################"<<std::endl;
    response.write(of);
    of.close();
    return o.str();
};

std::string CL_News_pool::CL_RSS_Quelle::strip_from_html(const std::string& s)
{
    static const boost::regex a("<a.*</a>");
    static const boost::regex crap("</?[^>]*>");
    if(s.npos==s.find("<"))return s;  //do expensive regex only if needed
    std::string s1=boost::regex_replace(s, a, "");
    return boost::regex_replace(s1, crap, "");
}

time_t CL_News_pool::CL_RSS_Quelle::timestrings_to_time_t(const std::string& tstring)
{
    Poco::DateTime dateTime;
    int tzd=0;
    Poco::DateTimeParser::parse(tstring,dateTime, tzd);
    dateTime.makeUTC(tzd);
    Poco::Timestamp ts=dateTime.timestamp();
    return ts.epochTime();
}

//////////////////////////////////////////////////////////////////////////////
//
// process_mem_usage(double &, double &) - takes two doubles by reference,
// attempts to read the system-dependent data for a process' virtual memory
// size and resident set size, and return the results in KB.
//
// On failure, returns 0.0, 0.0
// code by Don Wakefield from
// http://stackoverflow.com/questions/669438/how-to-get-memory-usage-at-run-time-in-c

void CL_News_pool::process_mem_usage(double& vm_usage, double& resident_set)
{

    using std::ios_base;
    using std::ifstream;
    using std::string;

    vm_usage     = 0.0;
    resident_set = 0.0;

    // 'file' stat seems to give the most reliable results
    //
    ifstream stat_stream("/proc/self/stat",ios_base::in);

    // dummy vars for leading entries in stat that we don't care about
    //
    string pid, comm, state, ppid, pgrp, session, tty_nr;
    string tpgid, flags, minflt, cminflt, majflt, cmajflt;
    string utime, stime, cutime, cstime, priority, nice;
    string O, itrealvalue, starttime;

    // the two fields we want
    //
    unsigned long vsize;
    long rss;

    stat_stream >> pid >> comm >> state >> ppid >> pgrp >> session >> tty_nr
    >> tpgid >> flags >> minflt >> cminflt >> majflt >> cmajflt
    >> utime >> stime >> cutime >> cstime >> priority >> nice
    >> O >> itrealvalue >> starttime >> vsize >> rss; // don't care about the rest

    stat_stream.close();

    long page_size_kb = sysconf(_SC_PAGE_SIZE) / 1024; // in case x86-64 is configured to use 2MB pages
    vm_usage     = vsize / 1024.0;
    resident_set = rss * page_size_kb;
}


